package com.ruoyi.my.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.my.domain.Login;
import com.ruoyi.my.domain.Student;
import com.ruoyi.my.service.ILoginService;
import com.ruoyi.my.service.IStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 学生注册控制器
 */
@RestController
@RequestMapping("/student")
public class StudentRegisterController {
    
    private static final Logger logger = LoggerFactory.getLogger(StudentRegisterController.class);
    
    @Autowired(required = false)
    private IStudentService studentService;
    @Autowired(required = false)
    private ILoginService loginService;
    
    /**
     * 学生注册
     * @param registerData 注册数据
     * @return 结果
     */
    @PostMapping("/register")
    public AjaxResult studentRegister(@RequestBody JSONObject registerData) {
        try {
            System.out.println("================== 学生注册请求 ==================");
            System.out.println("接收时间: " + new java.util.Date());
            System.out.println("注册数据: " + registerData);
            
            // 获取前端传来的数据
            String name = registerData.getString("name");
            Integer sex = registerData.getInteger("sex");  // 性别：0=男，1=女
            String studentId = registerData.getString("studentId");
            String phone = registerData.getString("phone");
            String className = registerData.getString("className");
            String openId = registerData.getString("openId");  // 微信 OpenID
            
            // 数据验证
            if (name == null || name.trim().isEmpty()) {
                return AjaxResult.error("姓名不能为空");
            }
            if (sex == null) {
                return AjaxResult.error("性别不能为空");
            }
            if (sex != 0 && sex != 1) {
                return AjaxResult.error("性别值不正确（0=男，1=女）");
            }
            if (studentId == null || studentId.trim().isEmpty()) {
                return AjaxResult.error("学号不能为空");
            }
            if (phone == null || phone.trim().isEmpty()) {
                return AjaxResult.error("手机号不能为空");
            }
            if (className == null || className.trim().isEmpty()) {
                return AjaxResult.error("班级不能为空");
            }
            
            // 验证手机号格式
            if (!phone.matches("^1[3-9]\\d{9}$")) {
                return AjaxResult.error("手机号格式不正确");
            }
            
            System.out.println("姓名: " + name);
            System.out.println("性别: " + sex + " (" + (sex == 0 ? "男" : "女") + ")");
            System.out.println("学号: " + studentId);
            System.out.println("手机号: " + phone);
            System.out.println("班级: " + className);
            System.out.println("OpenID: " + (openId != null ? openId : "未提供"));
            // 检查学号是否已存在
            Student existStudent = studentService.selectStudentByStudentId(Long.valueOf(studentId));
            if (existStudent != null) {
                System.out.println("❌ 学号已存在");
                System.out.println("=============================================");
                return AjaxResult.error("该学号已注册");
            }
            //创建登录对象
            Login login = new Login();
            // 创建学生对象
            Student student = new Student();
            student.setName(name);
            student.setSex(Long.valueOf(sex));
            student.setIdNumer(studentId);
            student.setPhone(phone);
            student.setClassName(className);
            if (openId != null && !openId.trim().isEmpty()) {
                login.setWeixinId(openId);// 保存微信 OpenID
                login.setStudentId(Long.valueOf(studentId));
            }

            // 保存到数据库
            int result = studentService.insertStudent(student);
            int result1 = loginService.insertLogin(login);
            if (result > 0&&result1 > 0) {
                System.out.println("✅ 注册成功，学生ID: " + student.getIdNumer());
                System.out.println("=============================================");

                AjaxResult ajaxResult = AjaxResult.success("注册成功");
                ajaxResult.put("studentId", student.getId());
                ajaxResult.put("name", name);
                return ajaxResult;
            } else {
                System.out.println("❌ 注册失败");
                System.out.println("=============================================");
                return AjaxResult.error("注册失败，请重试");
            }
        } catch (Exception e) {
            System.err.println("【错误】学生注册失败: " + e.getMessage());
            logger.error("学生注册失败", e);
            e.printStackTrace();
            return AjaxResult.error("注册失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查学号是否存在
     * @param studentId 学号
     * @return 结果
     */
    @GetMapping("/checkStudentId/{studentId}")
    public AjaxResult checkStudentId(@PathVariable String studentId) {
        try {
            if (studentService != null) {
                Student student = studentService.selectStudentByStudentId(Long.valueOf(studentId));
                if (student != null) {
                    return AjaxResult.success("学号已存在", false);
                } else {
                    return AjaxResult.success("学号可用", true);
                }
            } else {
                return AjaxResult.success("学号可用（测试模式）", true);
            }
        } catch (Exception e) {
            logger.error("检查学号失败", e);
            return AjaxResult.error("检查失败");
        }
    }
}

